package com.zmn.plat.admin.controller.servcategory;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zmn.common.dto2.ResponseDTO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.entity.product.ServProductQuery;
import com.zmn.plat.model.entity.servcategory.ServCategory;
import com.zmn.plat.model.vo.servcategory.ServCategoryVO;

/**
 * @author duanzuocai
 * @version v1.0
 * @since 2018/10/20 9:15
 */
@Controller
@RequestMapping("/serv/showCateg/")
public class ShowServCategoryModifyController extends ServCategoryBaseController {

    private Logger logger = LoggerFactory.getLogger(ShowServCategoryModifyController.class);

    @RequestMapping(value = "updateStatus")
    @ResponseBody
    public ResponseDTO updateStatus(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam(value = "ids", defaultValue = "") String ids, @RequestParam(value = "status", defaultValue = "0") int status) {

        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的分类！");
        }

        List<Integer> arrayIds = StringUtil.convertStrsToList(ids);

        if (Objects.equals(GlobalConsts.NO, status)) {
            ServProductQuery query = new ServProductQuery();
            query.setServCategIds(arrayIds);
            query.setStatus(GlobalConsts.YES);
            query.setShowType(ProductDict.EC_PRODUCT_TYPE);
            List<ServProduct> servProducts = servProductService.listByQuery(query);
            List<Integer> servCategIds = servProducts.stream().map(ServProduct::getServCategId).distinct().collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(servCategIds)) {
                return ResponseDTO.fail("服务分类下的产品需全部下架");
            }
        }

        servCategoryService.updateShowStatusBatch(arrayIds, status, getMcStaffRealName());

        return ResponseDTO.success(true,"操作成功！");
    }

    @RequestMapping(value = "updateSort")
    @ResponseBody
    public ResponseDTO updateSort(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer categId, @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (categId == 0) {
            return ResponseDTO.fail("请选择要更改排序的分类！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置分类排序值！");
        }

        servCategoryService.updateShowSortKey(categId, sort, getMcStaffRealName());
        return ResponseDTO.success(true,"操作成功！");
    }

    @RequestMapping(value = "updateFirstLetter")
    @ResponseBody
    public ResponseDTO updateFirstLetter(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer categId,
        @RequestParam(value = "firstLetter", defaultValue = "") String firstLetter) {

        if (categId == 0) {
            return ResponseDTO.fail("请选择要更改首字母的分类！");
        }
        if (firstLetter.isEmpty()) {
            return ResponseDTO.fail("请设置首字母！");
        }

        servCategoryService.updateShowFirstLetterKey(categId, firstLetter, getMcStaffRealName());
        return ResponseDTO.success(true,"操作成功！");
    }

    @RequestMapping(value = "updateShowSimpleSpell")
    @ResponseBody
    public ResponseDTO updateShowSimpleSpell(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "id", defaultValue = "0") Integer categId,
                                         @RequestParam(value = "simpleSpell", defaultValue = "") String simpleSpell) {

        if (categId == 0) {
            return ResponseDTO.fail("请选择要更改的分类！");
        }
        if (StringUtil.isBlank(simpleSpell)) {
            return ResponseDTO.fail("请设置简称！");
        }

        servCategoryService.updateShowSimpleSpellByKey(categId, simpleSpell.toUpperCase(), getMcStaffRealName());
        return ResponseDTO.success(true,"操作成功！");
    }

    @RequestMapping(value = "updateName")
    @ResponseBody
    @SuppressWarnings("Duplicates")
    public ResponseDTO updateName(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer categId, @RequestParam(value = "name", defaultValue = "0") String name) {
        if (categId == 0) {
            return ResponseDTO.fail("请选择要更改排序的分类！");
        }
        if (StringUtils.isEmpty(name)) {
            return ResponseDTO.fail("请设置名称值！");
        }

        servCategoryService.updateNameKey(categId, name, getMcStaffRealName());

        return ResponseDTO.success(true,"操作成功！");
    }

    @RequestMapping(value = "addEdit")
    @ResponseBody
    public ResponseDTO addEdit(HttpServletRequest request, HttpServletResponse response, @RequestBody ServCategory category) {
        Date now = DateUtil.getNow();

        Integer categId = category.getCategId();

        check(category);

        try {
            if (categId == null) {
                return ResponseDTO.fail("前台分类不存在！");
            } else if (category.getTariffStatus() == null) {
                return ResponseDTO.fail("计价器状态不能为空！");
            } else {
                servCategoryBService.updateFrontByKey(category, getMcStaffRealName());
            }

            return ResponseDTO.success(true,"操作成功！");
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        } catch (org.springframework.dao.DuplicateKeyException ex) {
            logger.error("前台服务类型【{}】已经存在，不能重复添加！", category.getName());
            return ResponseDTO.fail("前台服务类型已经存在，不能重复添加！");
        } catch (Exception ex) {
            logger.error("[zmn]新增/修改前台产品分类失败,category:{},ex:{}", category, ex.getMessage(), ex);
            return ResponseDTO.fail("操作失败！");
        }
    }

    @RequestMapping(value = "classifyProduct")
    @SuppressWarnings("Duplicates")
    public ModelAndView list(@RequestParam(value = "servCategId", defaultValue = "0") Integer servCategId) {
        List<BaseCategory> categOnes = baseCategoryService.listByParentIdForShow(GlobalConsts.TOP_ID, GlobalConsts.YES);
        List<ServCategoryVO> servAssCategoryItems = servAssCategoryService.listClassificationLevelTwoForShow();
        List<ServCategoryVO> servAssCategoryByServId =
            servAssCategoryService.findServAssCategoryByServIdAndShowType(servCategId, ProductConsts.EC_PRODUCT_TYPE);
        ServCategory servCategory = servCategoryService.findByKey(servCategId);
        if (servCategory == null) {
            servCategory = new ServCategory();
        }
        Map<Integer, List<ServCategoryVO>> map =
            servAssCategoryItems.stream().collect(Collectors.groupingBy(ServCategoryVO::getCategOneId));

        for (Map.Entry<Integer, List<ServCategoryVO>> entry : map.entrySet()) {
            for (ServCategoryVO servCategoryVo : entry.getValue()) {
                for (ServCategoryVO innerServCategoryVO : servAssCategoryByServId) {
                    if (innerServCategoryVO.getCategOneId().equals(servCategoryVo.getCategOneId())
                        && innerServCategoryVO.getCategId().equals(servCategoryVo.getCategId())) {
                        servCategoryVo.setRelated(true);
                        break;
                    } else {
                        servCategoryVo.setRelated(false);
                    }
                }

            }
        }

        ModelAndView mav = new ModelAndView("servcategroy/show/classifyproduct");

        mav.addObject("servCategId", servCategId);
        mav.addObject("servCategory", servCategory);
        mav.addObject("items", servAssCategoryItems);
        mav.addObject("categOnes", categOnes);
        mav.addObject("flag", 2);
        mav.addObject("map", map);
        return mav;
    }

    private void check(ServCategory category) {
        if (!NumberUtil.isPositiveInteger(category.getSort())) {
            category.setSort(GlobalConsts.TOP_ID);
        }
    }
}
